#pragma once
#include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <functional>
#include <pthread.h>
#include <cstring>
#include <cstdio>
#include <string>
static uint32_t number = 1; // bug
class thread
{
    using func_t = std::function<void()>;

private:
    void EnableDetach()
    {
        std::cout << "线程被分离了" << std::endl;
        _isdetach = true;
    }
    void EnableRunning()
    {
        _isrunning = true;
    }
    static void *Routine(void *args)
    {
        thread *self = (thread *)args;
        self->EnableRunning();
        if (self->_isdetach)
        {
            self->Detach();
        }
        pthread_setname_np(self->_id, self->_name.c_str());
        self->_func();
        return nullptr;
    }
public:
    thread(func_t func)
        : _id(0), _isrunning(false), _isdetach(false), _func(func), _res(nullptr)
    {
        _name = "thread-" + std::to_string(number++);
    }
    bool Start() // 创建线程
    {
        if (_isrunning)
        {
            return false;
        }
        int n = pthread_create(&_id, nullptr, Routine, this);
        if (n != 0)
        {
            std::cerr << "pthread_create error" << std::endl;
            return false;
        }
        else
        {
            std::cout << _name << " creat success" << std::endl;
            return true;
        }
    }
    void Detach() // 开启线程分离模式
    {
        if (_isdetach)
        {
            return;
        }
        if (_isrunning)
        {
            pthread_detach(_id);
        }
        EnableDetach();
    }
    bool Stop() // 终止线程
    {
        if (_isrunning)
        {
            int n = pthread_cancel(_id);
            if (n != 0)
            {
                std::cerr << "pthread_cancel error" << std::endl;
                return false;
            }
            else
            {
                _isrunning = false;
                std::cout << _name << " stop" << std::endl;
                return true;
            }
        }
        return false;
    }
    void Join() // 等待线程
    {
        if (_isdetach) // 分离模式下的线程不需要被等待
        {
             std::cout << "你的线程已经是分离的了,不能进行join" << std::endl;
            return;
        }
        int n = pthread_join(_id, &_res);
        if (n != 0)
        {
            std::cerr << "create thread error: " << strerror(n) << std::endl;
        }
        else
        {
            std::cout << "join success" << std::endl;
        }
    }
    ~thread()
    {
    }

private:
    pthread_t _id;
    void *_res;
    std::string _name;
    bool _isrunning;
    bool _isdetach;
    func_t _func;
};

